package com.dtu.distributed.thread;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

import com.dtu.distributed.controller.TempController;
import com.dtu.distributed.enums.Action;

/*
 * SHOULD BE USED TO RECEIVE AND CALCULATE THE AVG - ONLY STARTED IF ADMIN
 */
public class AdminThread extends Thread {

	private DatagramSocket socket;
	private boolean runThread = true;	

	public AdminThread() {
//		TempController.bindClientConnection();
		setupListener();
	}

	public void setupListener() {
		try {
			socket = new DatagramSocket(TempController.adminTemperaturePort);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void run() {
		System.out.println("Admin thread running");
		while (runThread) {
			byte[] buffer = new byte[1000];
			DatagramPacket messageIn = new DatagramPacket(buffer, buffer.length);
			try {
				socket.receive(messageIn);
				System.out.println("Sender address: " + messageIn.getSocketAddress() + " , i'm admin: " + TempController.isAdmin());
				
				String message = new String(messageIn.getData());
				String[] messageParts = message.split(":");
					
				Action action = Action.getAction(messageParts[0].trim());				
				if (Action.TEMPERATURE == action) {
					if (TempController.isAdmin()){
						int temperature = Integer.parseInt(messageParts[1].trim());
						TempController.updateAvg(temperature);
						System.out.println("Recieved temp: " + temperature);
					}
				}				
			} catch (IOException e) {
				e.printStackTrace();
			}							
		}
	}
		
}